package ken.spring.cloud.alibaba;

import com.alibaba.cloud.stream.binder.rocketmq.constant.RocketMQConst;
import org.apache.rocketmq.common.message.MessageConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.MimeTypeUtils;

/**
 * <ul>
 * <li>Title: SendService</li>
 * <li>Description: TODO </li>
 * </ul>
 *
 * @author swc
 * @date 2022-07-08 11:28
 */
@Service
public class MqSendService {

    @Autowired
    private  MySource mySource;


    /**
     * 功能描述: 默认的发送消息
     * @param msg
     * @return: boolean
     * @author: swc
     * @date: 2022-07-08 11:36
    */
    public boolean sendMsg(String msg) throws Exception {
        MessageBuilder builder = MessageBuilder.withPayload(msg)
                .setHeader(MessageConst.PROPERTY_TAGS, "tagStr");
        Message message = builder.build();
        mySource.msgOutput1().send(message);
        return true;
    }

    /**
     * 功能描述: 发送消息
     * @param msg 支持文本或对象
    * @param tag
     * @return: boolean
     * @author: swc
     * @date: 2022-07-08 11:36
    */
    public <T> boolean  sendMsgTags(T msg,String tag) throws Exception {
        Message message = MessageBuilder.withPayload(msg)
                .setHeader(MessageConst.PROPERTY_TAGS, tag)
                .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON)
                .build();
        mySource.msgOutput1().send(message);
        return true;
    }

    /**
     * 功能描述: 发送支持事务的消息
     * @param msg 支持文本或对象
    * @param num
     * @return: boolean
     * @author: swc
     * @date: 2022-07-08 11:37
    */
    public  <T>  boolean sendTransactionalMsg(T msg, int num){
        MessageBuilder builder = MessageBuilder.withPayload(msg)
                .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON);
        builder.setHeader(RocketMQConst.USER_TRANSACTIONAL_ARGS, "binder");
        builder.setHeader("test", String.valueOf(num));
        Message message = builder.build();
        mySource.msgTransactionalOutput2().send(message);
        return true;
    }


}
